package com.ecp.commons.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.ecp.commons.bean.Advertising;
import com.ecp.commons.bean.Page;
import com.ecp.commons.db.GenericServiceImpl;
import com.ecp.commons.storage.StorageServiceFactory;
import com.ecp.util.DateUtil;

@Repository("advertisingService")
public class AdvertisingServiceImpl extends GenericServiceImpl<Advertising> implements
		AdvertisingService {

	@Override
	public List<Advertising> getAdvertisingByColumnId(int columnId, Page page) {
		StringBuffer advQuery = new StringBuffer(
				"SELECT cms_advertising.* FROM cms_advplace,cms_advertising");
		Object[] args = null;
		String nowDate = DateUtil.getNowStringDate();
		advQuery.append(" WHERE 1=1");
		advQuery.append(" AND cms_advplace.ID = cms_advertising.ADVPLACEID");
		advQuery.append(" AND cms_advplace.ADVPLACETYPEID = ? AND cms_advplace.isEnabled = 1 AND cms_advertising.IFSHOW = 1");
		advQuery.append(" AND (cms_advertising.DEFAULTFLAG = 1 OR (cms_advertising.DEFAULTFLAG = 0");
		advQuery.append(" AND (cms_advertising.BEGINTIME IS NULL OR cms_advertising.BEGINTIME <= ? ) ");
		advQuery.append(" AND (cms_advertising.ENDTIME IS NULL OR cms_advertising.ENDTIME >= ? ))) ");
		advQuery.append(" ORDER BY cms_advplace.SORTORDER, cms_advertising.SORTORDER");
		args = new Object[] { columnId, nowDate, nowDate };
		List<Advertising> advertisings = new ArrayList<Advertising>();
		try {
			advertisings = this.getEntityList(advQuery.toString(), args, new Advertising(), page);
		} catch (Exception e) {
			e.printStackTrace();
		}
		String advBasePath = StorageServiceFactory._ADIMAGESSERVICE.getShowBasePath();
		for (Advertising adv : advertisings) {
			if (!adv.getPicsPath().contains(advBasePath)) {
				adv.setPicsPath(advBasePath + adv.getPicsPath());
			}
		}
		return advertisings;
	}
}
